    /*  
    championBuilder - Champions Online character planner.
    Copyright (C) 2009 Moritz Hartmeier
    
    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.
    
    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.
    
    You can find the GNU General Public License in the data folder.
    */


package ch.zarzu.champions.builder;

import java.awt.Color;
import java.io.File;
import java.util.HashMap;
import java.util.LinkedList;

import javax.swing.JOptionPane;

import ch.zarzu.util.AppPath;


public class PrefLink {
    public String default_path, app_path;
    private SystemLink sys_link;
    private File default_file, app_file, pref_file;
    private HashMap<String, String> prefs;
    private static PrefLink instance = null;
    
    /**
     * determines the location of the preference file and reads or creates it
     */
    private PrefLink() {
        sys_link = SystemLink.getInstance();
        
        prefs = new HashMap<String, String>();
        default_path = javax.swing.filechooser.FileSystemView.getFileSystemView().getDefaultDirectory().getAbsolutePath().replace("\\", "/") + "/";
        app_path = AppPath.get();
        
        default_file = new File(default_path + "championBuilder/preferences.txt");
        app_file = new File(app_path + "data/preferences.txt");
        if(app_file.exists()) {
            pref_file = app_file;
            parse_prefs(pref_file);
        } else if (default_file.exists()){
            pref_file = default_file;
            parse_prefs(pref_file);
        } else {
            new File(app_path + "temp").mkdir();
            if(new File(app_path + "temp").exists()) {
                pref_file = app_file;
                new File(app_path + "builds").mkdir();
                setPreference("save_path", app_path + "builds");
            } else {
                pref_file = default_file;
                new File(default_path + "championBuilder/builds").mkdirs();
                setPreference("save_path", default_path + "championBuilder/builds");
            }
        }
        new File(app_path + "temp").delete();
        
        //determine language
        HashMap<String, String> languages = sys_link.getString("languages");
        if(!languages.containsKey(getPreference("language"))) {
            
            Object[] choices = sys_link.getString("languages").values().toArray();
            String input = (String) JOptionPane.showInputDialog(null, "Choose language",
                "Choose your preferred language:", JOptionPane.QUESTION_MESSAGE, null, // Use
                                                                                // default
                                                                                // icon
                choices,
                "English");
            if(input != null) {
                for(String s : languages.keySet()) {
                    if(languages.get(s).equals(input))
                        setPreference("language", s);
                }
            } else {
                setPreference("language", "english");
            }
        }
        String background_color = getPreference("background");
        if(background_color == "") {
            background_color += fillToTwoDigits(Integer.toHexString(11));
            background_color += fillToTwoDigits(Integer.toHexString(139));
            background_color += fillToTwoDigits(Integer.toHexString(226));
            setPreference("background", background_color);
        }
        int rgb = Integer.parseInt(background_color, 16);
        App.setBackground(new Color(rgb));
        
        System.out.println(getPreference("language"));
    }
    
    /**
     * parses the preference file and populates the HashMap with the unique preference keys and their values
     * preference file format is like: prefkey: somevalue
     */
    private void parse_prefs(File f) {
        String input = FileSystemWrapper.readFile(f);
        
        String[] pref_array = input.split("[\n]");
        String[] pref_tuple;
        for(String s : pref_array) {
            pref_tuple = s.split("[:]", 2);
            if(pref_tuple.length == 2) {
                prefs.put(pref_tuple[0], pref_tuple[1].trim());
            }
        }
    }
    
    
    public void updateLastSaved(String s) {
        if(!getPreference("last_saved_0").equals("")) {
            for(int i = 0; i < 5; i++) {
                if(getPreference("last_saved_" + i).equals(s))
                    setPreference("last_saved_" + i, "");
            }
            for(int i = 4; i >= 0; i--) {
                if(getPreference("last_saved_" + (i + 1)).equals("")) {
                    setPreference("last_saved_" + (i + 1), getPreference("last_saved_" + i));
                    setPreference("last_saved_" + i, "");
                }
            }
        }
        setPreference("last_saved_0", s);
        
        if(!s.equals(""))
            setPreference("save_path", new File(s).getParent());
    }
    
    public LinkedList<String> getRecentSaved() {
        LinkedList<String> list = new LinkedList<String>();
        
        for(int i = 0; i < 5; i++) {
            list.add(getPreference("last_saved_" + i));
        }
        return list;
    }
    
    /**
     * writes all preferences in the file
     */
    private void writePreferences() {
        String output = "";
        
        for(String s : prefs.keySet()) {
            output += s + ": " + prefs.get(s) + "\n";
        }
        FileSystemWrapper.writeFile(pref_file, output);
    }
    
    /**
     * returns a preference setting
     */
    public String getPreference(String k) {
        if(prefs.containsKey(k))
            return prefs.get(k);
        else
            return "";
    }
    
    /**
     * sets a preference setting
     */
    public void setPreference(String k, String v) {
        prefs.put(k, v);
        writePreferences();
    }

    public boolean hasLastSaved() {
        return !getPreference("last_saved_0").equals("");
    }
    
    public String getLastSaved() {
        if(hasLastSaved())
            return getPreference("last_saved_0");
        else
            return getPreference("last_saved_1");
    }
    
    public String getSaveFolder() {
        return getPreference("save_path");
    }
    
    public String getLanguageFolder() {
        return sys_link.getString("language_folders").get(getPreference("language"));
    }
    
    public String getLanguage() {
        return getPreference("language");
    }
    
    public String getPrefParent() {
        return pref_file.getParent();
    }
    
    private String fillToTwoDigits(String s) {
        if(s.length() == 1)
            s = "0" + s;
        return s;
    }
    
    /**
     * returns the singleton
     */
    public static PrefLink getInstance() {
        if(instance == null)
            instance = new PrefLink();
        return instance;
    }
}
